package com.shopping.controller;


import com.shopping.commons.CurUserInfo;
import com.shopping.commons.OrderParam;
import com.shopping.commons.Result;
import com.shopping.model.OrderDesc;
import com.shopping.model.Orders;
import com.shopping.service.OrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private HttpSession session;
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody OrderParam orderParam ){
        try {
            CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
            Orders order=orderParam.getOrder();
            //设置订单用户id
            order.setUser_id(curUserInfo.getUser_id());
            List<OrderDesc> orderDescList =new ArrayList<>();
            //将book_id封装到订单明细集合中
            for (int book_id :orderParam.getBook_ids()){
                OrderDesc orderDesc =new OrderDesc();
                orderDesc.setBook_id(book_id);
                orderDescList.add(orderDesc);
            }
            orderService.addOrder(order,orderDescList);
            return Result.success("订单添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500,"订单添加失败");
        }

    }
}
